package game.views;

import game.data.CDData;
import hx.display.IDataProider;
import hx.display.MovieClip;
import hx.display.Image;
import hx.ui.UIManager;
import openfl.Assets;
import hx.display.HBox;
import hx.display.Box;

/**
 * 冷却时间显示
 */
class CDDisplay extends Box implements IDataProider<CDDisplayData> {
	public var movie:MovieClip;

	public var data(get, set):CDDisplayData;

	public var __cdData:CDDisplayData;

	private var ____scaleX:Float = 1;

	var hBox = new HBox();

	public function set_data(v:CDDisplayData):CDDisplayData {
		hBox.verticalAlign = MIDDLE;
		this.addChild(hBox);
		hBox.removeChildren();

		if (v == null || v.groupKeys == null || v.groupKeys.length == 0) {
			if (movie != null)
				movie.visible = false;
			return null;
		}

		for (key in v.groupKeys) {
			var bitmapData = UIManager.getBitmapData("keys_atlas:" + String.fromCharCode(key));
			var image = new Image(bitmapData);
			hBox.addChild(image);
		}

		hBox.updateLayout();
		if (____scaleX > 0) {
			hBox.x = 0;
		} else {
			hBox.x = 345 - hBox.width;
		}

		if (movie == null) {
			var cdMovie = new MovieClip(UIManager.getAtlas("cdline").getBitmapDatasByName());
			this.movie = cdMovie;
		}
		this.addChild(movie);
		movie.visible = true;
		if (____scaleX > 0) {
			movie.x = hBox.children[hBox.numChildren - 1].x;
		} else {
			movie.x = hBox.x + hBox.children[hBox.numChildren - 1].x;
		}
		__cdData = v;
		return v;
	}

	public function get_data():CDDisplayData {
		return __cdData;
	}

	public function new(scaleX:Float = 1):Void {
		super();
		this.height = 120;
		this.____scaleX = scaleX;
		this.updateEnabled = true;
	}

	override function onUpdate(dt:Float) {
		super.onUpdate(dt);
		if (data != null && data.data != null) {
			this.setProgress(1 - data.data.cd / data.maxCd);
		}
	}

	/**
	 * 设置CD的进度
	 * @param progress 
	 */
	public function setProgress(progress:Float):Void {
		if (this.movie != null)
			this.movie.currentFrame = Std.int(progress * this.movie.totalFrame);
	}
}

typedef CDDisplayData = {
	groupKeys:Array<Int>,
	maxCd:Float,
	data:CDChildData
}
